package com.springmq.mq.juc;

import lombok.Data;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName : TestDemo01
 * @Author : lby
 * @Date: 2021/2/3 16:52
 * @Description : 生产者消费者关系
 * 当使用 wait 以及 notify方法时，必须使用synchronized
 */
public class TestDemo01 {
    public static void main(String[] args) {
        DemoTest demoTest = new DemoTest();
        ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,10, TimeUnit.MINUTES,new SynchronousQueue<Runnable>());
        ThreadPoolExecutor executor01=new ThreadPoolExecutor(10,10,10, TimeUnit.MINUTES,new SynchronousQueue<Runnable>());
        executor.execute(()->{
            for (int i = 0; i <5 ; i++) {
                try {
                    demoTest.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        executor01.execute(()->{
            for (int i = 0; i <5 ; i++) {
                try {
                    demoTest.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

    }
}

@Slf4j
@Data
class DemoTest{
    private int number=0;

    /**
     * 消费者去减
     */
    public synchronized void decrease() throws InterruptedException {
        // 判断等待
        // 为了防止虚假唤醒问题，使用while循环
        while (number<=0){
            this.wait();
        }
        // 执行业务
        log.info("消费者执行方法:{}",number);
        number--;
        // 通知别人
        this.notifyAll();
    }
    /**
     * 生产者去加
     */
    public synchronized void increase() throws InterruptedException {
        // 判断等待
        // 为了防止虚假唤醒问题，使用while循环
        while (number>0){
            this.wait();
        }
        // 执行业务
        log.info("生产者执行方法:{}",number);
        number++;
        // 通知别人
        this.notifyAll();
    }

}
